<?php

namespace Ktnw\sms\utils;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use Ktnw\sms\SmsApplication;

/**
 * 发送短信的工具类
 */
class SmsUtils
{

    /**
     * 阿里云发送手机短信
     * @param  $phone string 手机号
     * @param  $smsPrams array 发送短信的参数 数组
     * @param  $signName string 短信签名
     * @param  $msgType string 发送短信的模板
     * @return array
     * @throws
     */
    public static function sendSms(string $phone, array $smsPrams, string $signName, string $msgType): array
    {
        $r['opFlag'] = 'fail';
        $smsPrams    = json_encode($smsPrams, JSON_UNESCAPED_UNICODE);

        // 双高在线阿里云账号
        $accessKeyId     = Config::getConfigValue('smsConfig.sms_accessKey_id');
        $accessKeySecret = Config::getConfigValue('smsConfig.sms_accessKey_secret');
        $regionId        = Config::getConfigValue('smsConfig.sms_regionId');

        AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)
            ->regionId($regionId)
            ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId'      => $regionId,
                        'PhoneNumbers'  => $phone,
                        'SignName'      => $signName,
                        'TemplateCode'  => $msgType,
                        'TemplateParam' => $smsPrams,
                    ],
                ])
                ->request();
            $result = $result->toArray();
            if ($result['Code'] == 'OK') {
                $r['opFlag'] = 'success';
            }
        } catch (ClientException | ServerException $e) {
            $r['msg'] = $e->getErrorMessage();
        }
        return $r;
    }




    /**
     * 生成随机字符串
     * @param int $length 生成随机字符串的长度
     * @param string $char 组成随机字符串的字符串
     * @return string $string 生成的随机字符串
     */
    public static function strRand(int $length = 6, string $char = '0123456789')
    {
        if (!is_int($length) || $length < 0) {
            return false;
        }

        $string = '';
        for ($i = $length; $i > 0; $i--) {
            $string .= $char[mt_rand(0, strlen($char) - 1)];
        }
        return $string;
    }

}
